<script lang="ts" setup>
import { QForm, type FormItemRows } from '@meetjs/element-plus-kit'
import { type FormRules, ElMessage } from 'element-plus'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { addDept, updateDept } from '@/api/system/dept/index'
import type { DeptParams, DeptList } from '@/api/system/dept/type'

const emits = defineEmits<{
	refresh: []
}>()

const visible = ref(false)
const loading = ref(false)
const title = ref<'新增部门' | '编辑部门'>('新增部门')
const type = ref<'add' | 'edit'>('add')
const formRef = ref()
const baseFormData: DeptParams = {
	parentId: 0, // 0表示根部门
	deptName: '',
	orderNum: 0,
	leader: '',
	phone: '',
	email: '',
	status: 0,
	remark: ''
}
const dialogFormValue = ref<DeptParams>({ ...baseFormData })
const deptOptions = ref<DeptList[]>([])
const sysNormalDisable = ref<IGetDictsRes>([])

const dialogOptions = ref<FormItemRows[]>([
	{
		type: 'cascader',
		label: '上级部门',
		prop: 'parentId',
		col: 24,
		options: deptOptions as unknown as any,
		attrs: {
			placeholder: '请选择上级部门',
			clearable: true,
			'show-all-levels': false,
			props: {
				value: 'id',
				label: 'deptName',
				children: 'children',
				emitPath: false,
				checkStrictly: true
			}
		}
	},
	{
		type: 'input',
		label: '部门名称',
		prop: 'deptName',
		col: 12,
		attrs: {
			placeholder: '请输入部门名称',
			clearable: true
		}
	},
	{
		type: 'input-number',
		label: '显示排序',
		prop: 'orderNum',
		col: 12,
		attrs: {
			placeholder: '请输入排序号',
			min: 0,
			controls: false
		}
	},
	{
		type: 'input',
		label: '负责人',
		prop: 'leader',
		col: 12,
		attrs: {
			placeholder: '请输入负责人',
			clearable: true
		}
	},
	{
		type: 'input',
		label: '联系电话',
		prop: 'phone',
		col: 12,
		attrs: {
			placeholder: '请输入联系电话',
			clearable: true
		}
	},
	{
		type: 'input',
		label: '邮箱',
		prop: 'email',
		col: 12,
		attrs: {
			placeholder: '请输入邮箱地址',
			clearable: true
		}
	},
	{
		type: 'radio',
		label: '状态',
		prop: 'status',
		col: 12,
		options: sysNormalDisable as unknown as any
	}
])

const rules = reactive<FormRules<{ [k: string]: any }>>({
	parentId: [
		{
			required: true,
			message: '请选择上级部门'
		}
	],
	deptName: [
		{
			required: true,
			message: '请输入部门名称'
		}
	],
	orderNum: [
		{
			required: true,
			message: '请输入显示排序'
		}
	]
})

const init = (operationType: 'add' | 'edit', editForm?: DeptList, parentId?: number, deptTreeData?: DeptList[]) => {
	visible.value = true
	type.value = operationType
	title.value = operationType === 'add' ? '新增部门' : '编辑部门'

	// 使用传入的部门数据或默认空数组
	deptOptions.value = deptTreeData || []

	// 根据操作类型初始化表单数据
	if (operationType === 'edit' && editForm) {
		// 编辑模式：直接使用传入的数据
		dialogFormValue.value = { ...editForm }
	} else {
		// 新增模式：使用默认数据
		dialogFormValue.value = { ...baseFormData }
		if (parentId) {
			dialogFormValue.value.parentId = parentId
		}
	}

	// 清理表单验证状态
	setTimeout(() => {
		formRef.value?.clearValidate()
	})
}

const submit = () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			loading.value = true
			try {
				const apiFunc = type.value === 'add' ? addDept : updateDept
				await apiFunc({ ...dialogFormValue.value })
				const message = type.value === 'add' ? '新增成功' : '修改成功'
				ElMessage.success(message)
				visible.value = false
				emits('refresh')
			} catch (error) {
				console.error('部门保存失败:', error)
				ElMessage.error('保存失败，请重试')
			} finally {
				loading.value = false
			}
		}
	})
}

const getMethods = () => {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})
}

onMounted(() => {
	getMethods()
})

defineExpose({
	init
})
</script>
<template>
	<ElDialog
		v-model="visible"
		:title="title"
		:close-on-click-modal="false"
		width="800px"
	>
		<QForm
			ref="formRef"
			label-width="80px"
			:model="dialogFormValue"
			:form-options="dialogOptions"
			:rules="rules"
			:required="true"
			:gutter="20"
		/>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button
				type="primary"
				:loading="loading"
				@click="submit"
			>
				确定
			</el-button>
		</template>
	</ElDialog>
</template>

<style lang="scss" scoped></style>
